2023/12/23732字符

二叉树求和

var treenode = {
    value: 1,
    left: {
        value: 2,
        left: {
            value: 4,
        },
        right: {
            value: 5,
            left: {
                value: 7,
            },
            right: {
                value: 8,
            },
        },
    },
    right: {
        value: 3,
        right: {
            value: 6,
        },
    },
}
function sum(root) {
    let list = []
    if (root) list.push(root.value);
    if (root.left) {
        list = list.concat(sum(root.left));
    }
    if (root.right) {
        list = list.concat(sum(root.right));
    }
    return list;
}

console.log(sum(treenode));